import createFetchHook from "./hooks/createFetchHook";
// import createXMLHttpRequestHook from "./hooks/createXMLHttpRequestHook";
import createXHRHook  from "./hooks/createXHRHook";
import creteNodeHook from "./hooks/creteNodeHook";
const createXMLHttpRequestHook = createXHRHook
const requestMiddlewares = [];
const responseMiddlewares = [];

class RequestHook {
  add(fn:(ctx:ContextProps,handler:HandlerProps)=>void) {
    requestMiddlewares.push(fn)
    return this;
  }
}
class ResponseHook {
  add(fn:(ctx:ContextProps,handler:HandlerProps)=>void) {
    responseMiddlewares.push(fn)
    return this;
  } 
}
/**
 * 创建请求Hook
 * @returns 
 */
export function createRequestHook() {
  return new RequestHook();
}
/**
 * 创建返回Hook
 * @returns 
 */
export function createResponseHook() {
  return new ResponseHook();
}
const compose = (
  middleware: any[],
  ctx: ContextProps,
  handler: HandlerProps
) => {
  dispatch(0);
  function dispatch(i) {
    let fn = middleware[i];
    const _handler = {
      send(resBody:ResBodyType) {
        handler.send(resBody);
      },
      next() {
          dispatch(i + 1);
      },
    };
    if(fn){
      fn(ctx, _handler);
    }else{
      handler.next(ctx)
    }
  }
};
createFetchHook({
  onRequest(ctx:ContextProps, handler: HandlerProps) {
    // ctx.url = ctx.url+'?createFetchProxy'
    // ctx.resBody =JSON.stringify({"senssd":'ok ok'})
    compose(requestMiddlewares, ctx, handler);
  },
  onResponse(
    ctx: ContextProps,
    handler: { next: (arg0: any) => void; send: () => void }
  ) {
    compose(responseMiddlewares, ctx, handler);

    // ctx.resBody = JSON.stringify({mock:'body'})
    // console.log('onResponse',ctx)
    // handler.next(ctx)
  },
});
createXMLHttpRequestHook({
  onRequest(ctx: any, handler: any) {
    compose(requestMiddlewares, ctx, handler);

    // config.url = config.url+'?createXMLHttpRequest'
    // config.resBody =JSON.stringify({"senssd":'ok ok'})
    // console.log('config',config)
    // requestMiddlewares.forEach(fun=>{
    //    fun(config,handler)
    // })
    // handler.send(config.resBody)
    // handler.next(config)
  },
  onResponse(
    ctx: any,
    handler: { next: (arg0: any) => void; send: () => void }
  ) {
    compose(responseMiddlewares, ctx, handler);

    // config.resBody = JSON.stringify({mock:'body'})
    // config.resBody =`start--${ config.resBody}-->ok`
    // console.log('onResponse',config)
    // handler.next(config)
  },
});
creteNodeHook({
  onRequest(ctx, handler) {
    compose(requestMiddlewares, ctx, handler);

  },
  onResponse(ctx, handler) {
    compose(responseMiddlewares, ctx, handler);

  },
})
export default {
  createRequestHook,
  createResponseHook
};
